/**
 * redis 连接封装
 * const redis = require('../../modules/redis/index')
 * await redis.connect()
 * await redis.set('login-1', 'loginUser')
 * await redis.qiut()
 *
 * 过期时间设置 单位秒
 * await redis.set('login', 'loginUser', '10')
 * let result = await redis.get('login')
 * await redis.delete('login')
 * redis.qiut()
 */
const redis = require('redis')// Version 4.0.6
const config = require('../../../config')
class Redis{

    constructor() {
        // @ts-ignore
        this.client = redis.createClient({url: config.redisString})
        this.client.on('error', (err) => {
            console.log(err)
        })
    }
    //建立链接
    async connect() {
        try{
            await this.client.connect()
        }catch {
            //redis已经打开
        }
    }
    //断开链接
    async qiut() {
        try {
            await this.client.quit()
        } catch {
            //redis已经关闭
        }
    }
    //添加数据
    async set(key, value, time) {
        //判断value值是否是对象类型
        if (typeof value === 'object') {
            value = JSON.stringify(value)
        }
        //time为过期时间，可选
        time ? await this.client.set(key, value, {
            EX: time,
            NX: true
        }) : await this.client.set(key, value)
    }
    //获取数据
    async get(key) {
        return new Promise((resolve, reject) => {
            const data = this.client.get(key)
            if (data) {
                resolve(data)
            } else {
                reject(false)
            }
        })
    }
    //删除数据
    async delete(key) {
        await this.client.del(key)
    }
    //清空所有
    async cleanAll(){
        await this.client.flushAll()
    }
}

module.exports = new Redis()